home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12561 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  58 lines

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Sort Function
  5. Date: 1 Apr 1996 11:39:24 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4jpbdcINN16c@keats.ugrad.cs.ubc.ca>
  8. References: <4jmq99$cqi@freenet-news.carleton.ca>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4jmq99$cqi@freenet-news.carleton.ca>,
  12. Jerry Boyd <aq436@FreeNet.Carleton.CA> wrote:
  13. >
  14. >
  15. >How would I WRITE a function (called sort3) that would 
  16. >sort three integers (in assending order) by using pointers
  17. >and NOT arrays?
  18.  
  19. That would be blatantly inefficient. You can't count on the implementation to
  20. inline trivial functions. A comma-expression macro is called for:
  21.  
  22. #define SWP(x,y,tmp)        ((tmp) = (x), (x) = (y), y = (tmp))
  23. #define CSW(x,y,tmp)        ((x) > (y) ? SWP(x,y,tmp) : (tmp = tmp))
  24. #define sort3(a, b, c, tmp)    (CSW(a,b,tmp), CSW(b,c,tmp), CSW(a,b,tmp))
  25.  
  26. /*
  27.  * The drawback is that the client of sort3() has to provide temporary storage
  28.  * in the form of a fourth parameter. But the nice thing is that this will work
  29.  * on integral, floating-point and pointer types alike!
  30.  */
  31.  
  32. #include <stdio.h>
  33.  
  34. int main(int argc, char **argv)
  35.  
  36. {
  37.     int a, b, c, tmp;
  38.  
  39.     printf("enter three integers to be sorted: ");
  40.  
  41.     scanf("%d%d%d",&a,&b,&c);
  42.  
  43.     sort3(a,b,c,tmp);
  44.  
  45.     printf("your integers are: %d, %d, %d\n",a,b,c);
  46.  
  47.     return 0;
  48. }
  49.  
  50. The superflous (tmp = tmp) expression is required to supply the syntactic
  51. requirements of the conditional statement: the expressions are not optional
  52. like for example in for(;;).
  53.  
  54. Of course, I'm counting on the implementation to optimize away a useless
  55. assignment... :)
  56. -- 
  57.  
  58.